import 'package:craze/common/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:craze/stores/index.dart';
import 'package:craze/services/service_locator.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:craze/models/message_model.dart';
import 'package:craze/models/chat_model.dart';
import 'package:craze/services/user_service.dart';

class ChatView extends StatefulWidget {
  final bool isGroupChat;
  final String chatId;

  const ChatView({super.key, required this.chatId, this.isGroupChat = false});

  @override
  State<ChatView> createState() => _ChatViewState();
}

class _ChatViewState extends State<ChatView> {
  final ChatStore _chatStore = getIt<ChatStore>();
  final AuthStore _authStore = getIt<AuthStore>();
  final UserService _userService = getIt<UserService>();
  final MarineProtectionStore _emojiStore = getIt<MarineProtectionStore>();
  final TextEditingController _messageController = TextEditingController();
  bool _showEmojiPicker = false;

  @override
  void initState() {
    super.initState();
    _loadData();
    _markMessagesAsRead();
  }

  Future<void> _loadData() async {
    await _chatStore.loadChatMessages(widget.chatId);
    await _emojiStore.loadEmojis();
  }

  Future<void> _markMessagesAsRead() async {
    await _chatStore.markMessagesAsRead(widget.chatId);
  }

  void _toggleEmojiPicker() {
    setState(() {
      _showEmojiPicker = !_showEmojiPicker;
    });
  }

  Future<void> _sendMessage() async {
    final text = _messageController.text.trim();
    if (text.isNotEmpty) {
      await _chatStore.sendMessage(widget.chatId, text);
      _messageController.clear();
    }
  }

  Future<void> _sendEmoji(String emojiPath) async {
    await _chatStore.sendMessage(
      widget.chatId,
      emojiPath,
      isEmoji: true,
      emojiPath: emojiPath,
    );
    setState(() {
      _showEmojiPicker = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildTitleBar(),
              _buildChatHeader(),
              Divider(color: Colors.white.withAlpha(50), thickness: 1.h),
              // 消息列表
              Expanded(
                child: Observer(
                  builder: (_) {
                    final messages =
                        _chatStore.chatMessages[widget.chatId] ?? [];
                    return ListView.builder(
                      padding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 10.h,
                      ),
                      itemCount: messages.length,
                      itemBuilder: (context, index) {
                        return _buildMessageItem(messages[index]);
                      },
                    );
                  },
                ),
              ),
              _buildInputArea(),
              if (_showEmojiPicker) _buildEmojiPicker(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildTitleBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Icon(MyIcons.iconBack, color: Colors.white, size: 20.sp),
          ),
          Expanded(
            child: Center(
              child: Text(
                'Chat',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 22.sp,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                  fontWeight: FontWeight.w400,
                  height: 1.36,
                ),
              ),
            ),
          ),
          SizedBox(width: 20.sp),
        ],
      ),
    );
  }

  Widget _buildChatHeader() {
    ChatModel? chat;
    try {
      chat =
          _chatStore.currentChat ??
          _chatStore.chats.firstWhere((c) => c.id == widget.chatId);
    } catch (e) {
      chat = null;
    }
    if (chat == null) return SizedBox.shrink();
    if (chat.isGroupChat) {
      return Padding(
        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
        child: Column(
          children: [
            Stack(
              children: [
                Container(
                  width: 58.w,
                  height: 58.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.rectangle,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(100.r),
                      topRight: Radius.circular(100.r),
                      bottomLeft: Radius.circular(30.r),
                      bottomRight: Radius.circular(100.r),
                    ),
                    image: DecorationImage(
                      image: AssetImage(chat.groupAvatar ?? MyImages.touxiang1),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                Positioned(
                  right: 0,
                  bottom: 0,
                  child: Container(
                    width: 18.w,
                    height: 18.w,
                    decoration: const BoxDecoration(
                      color: Colors.blue,
                      shape: BoxShape.circle,
                    ),
                    child: Center(
                      child: Icon(
                        Icons.group,
                        color: Colors.white,
                        size: 12.sp,
                      ),
                    ),
                  ),
                ),
              ],
            ),
            SizedBox(height: 5.h),
            Text(
              chat.groupName ?? 'Group Chat',
              style: TextStyle(
                color: Colors.white,
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                fontFamily: GoogleFonts.inter().fontFamily,
              ),
            ),
          ],
        ),
      );
    } else {
      // 私聊
      final otherUserId = chat.participantIds.firstWhere(
        (id) => id != _authStore.currentUser?.id,
        orElse: () => '',
      );
      final otherUser = _userService.getUserById(otherUserId);
      final currentUser = _authStore.currentUser;
      return Container(
        color: const Color(0xFF0A1229),
        padding: EdgeInsets.only(top: 15.h, bottom: 15.h),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              left: 55.w,
              child: Text(
                currentUser?.name ?? '',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                ),
              ),
            ),
            Positioned(
              right: 55.w,
              child: Text(
                otherUser?.name ?? 'Unknown',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w600,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                ),
              ),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.rectangle,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.r),
                      topRight: Radius.circular(30.r),
                      bottomLeft: Radius.circular(30.r),
                      bottomRight: Radius.circular(10.r),
                    ),
                    image: DecorationImage(
                      image: AssetImage(
                        currentUser?.avatar ?? MyImages.touxiang1,
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
                SizedBox(width: 4.w),
                Container(
                  width: 60.w,
                  height: 60.w,
                  decoration: BoxDecoration(
                    shape: BoxShape.rectangle,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(30.r),
                      topRight: Radius.circular(30.r),
                      bottomLeft: Radius.circular(10.r),
                      bottomRight: Radius.circular(30.r),
                    ),
                    image: DecorationImage(
                      image: AssetImage(
                        otherUser?.avatar ?? MyImages.touxiang1,
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    }
  }

  Widget _buildMessageItem(MessageModel message) {
    final isCurrentUser = message.senderId == _authStore.currentUser?.id;
    final sender = _userService.getUserById(message.senderId);
    return Padding(
      padding: EdgeInsets.only(bottom: 15.h),
      child: Row(
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isCurrentUser)
            Container(
              width: 42.w,
              height: 42.w,
              margin: EdgeInsets.only(right: 8.w),
              decoration: BoxDecoration(
                shape: BoxShape.rectangle,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(100.r),
                  topRight: Radius.circular(100.r),
                  bottomLeft:
                      isCurrentUser
                          ? Radius.circular(30.r)
                          : Radius.circular(100.r),
                  bottomRight:
                      isCurrentUser
                          ? Radius.circular(100.r)
                          : Radius.circular(30.r),
                ),
                image: DecorationImage(
                  image: AssetImage(sender?.avatar ?? MyImages.touxiang1),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          Flexible(
            child: Container(
              padding:
                  message.isEmoji
                      ? EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h)
                      : EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration:
                  isCurrentUser
                      ? ShapeDecoration(
                        color: const Color(0xFF121325),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(30.r),
                            topRight: Radius.circular(30.r),
                            bottomLeft: Radius.circular(30.r),
                            bottomRight: Radius.circular(4.r),
                          ),
                        ),
                        shadows: [
                          BoxShadow(
                            color: const Color(0x99055FC6),
                            blurRadius: 7,
                            offset: const Offset(0, 1),
                            spreadRadius: 0,
                          ),
                        ],
                      )
                      : ShapeDecoration(
                        gradient: LinearGradient(
                          begin: Alignment(0.50, 0.00),
                          end: Alignment(0.50, 0.86),
                          colors: [
                            const Color(0xFF0076FF).withAlpha(60),
                            const Color(0xFF045EC6).withAlpha(60),
                          ],
                        ),
                        shape: RoundedRectangleBorder(
                          side: const BorderSide(
                            width: 1,
                            color: Color(0xFF0076FF),
                          ),
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(30.r),
                            topRight: Radius.circular(30.r),
                            bottomLeft: Radius.circular(4.r),
                            bottomRight: Radius.circular(30.r),
                          ),
                        ),
                      ),
              child:
                  message.isEmoji
                      ? Image.asset(
                        message.emojiPath ?? '',
                        width: 40.w,
                        height: 40.w,
                      )
                      : Text(
                        message.content,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14.sp,
                          fontWeight: FontWeight.w400,
                          fontFamily: GoogleFonts.inter().fontFamily,
                        ),
                      ),
            ),
          ),
          if (isCurrentUser)
            Container(
              width: 42.w,
              height: 42.w,
              margin: EdgeInsets.only(left: 8.w),
              decoration: BoxDecoration(
                shape: BoxShape.rectangle,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(100.r),
                  topRight: Radius.circular(100.r),
                  bottomLeft:
                      isCurrentUser
                          ? Radius.circular(30.r)
                          : Radius.circular(100.r),
                  bottomRight:
                      isCurrentUser
                          ? Radius.circular(100.r)
                          : Radius.circular(30.r),
                ),
                image: DecorationImage(
                  image: AssetImage(sender?.avatar ?? MyImages.touxiang1),
                  fit: BoxFit.cover,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildEmojiPicker() {
    return Observer(
      builder: (_) {
        final emojis = _emojiStore.unlockedEmojis;
        return Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 20.h),
          color: const Color(0xFF0A1229),
          child: Column(
            children: [
              SizedBox(
                height: 60.h,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  padding: EdgeInsets.symmetric(horizontal: 20.w),
                  children:
                      emojis
                          .map((emoji) => _buildEmojiItem(emoji.path))
                          .toList(),
                ),
              ),
              SizedBox(height: 10.h),
              Text(
                'Complete tasks in marine protection activities to unlock more emojis',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w400,
                  fontFamily: GoogleFonts.inter().fontFamily,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildEmojiItem(String emojiPath) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: GestureDetector(
        onTap: () => _sendEmoji(emojiPath),
        child: Image.asset(emojiPath, width: 40.w, height: 40.w),
      ),
    );
  }

  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
      margin: EdgeInsets.all(10.w),
      decoration: BoxDecoration(
        color: Colors.black.withAlpha(100),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.blue.withAlpha(100), width: 1.w),
      ),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              controller: _messageController,
              style: TextStyle(color: Colors.white, fontSize: 14.sp),
              decoration: InputDecoration(
                hintText: 'Say something',
                hintStyle: TextStyle(color: Colors.grey, fontSize: 14.sp),
                border: InputBorder.none,
                contentPadding: EdgeInsets.symmetric(horizontal: 10.w),
              ),
            ),
          ),
          IconButton(
            onPressed: _toggleEmojiPicker,
            icon: Icon(MyIcons.iconSmile, color: Colors.white, size: 28.sp),
          ),
          GestureDetector(
            onTap: _sendMessage,
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.86),
                  colors: [const Color(0xFF0076FF), const Color(0xFF045EC6)],
                ),
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Text(
                'Send',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w400,
                  fontFamily: GoogleFonts.mochiyPopOne().fontFamily,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
